<template>
  <div class="cart-container">
    <div class="cart-header">
      <h2>我的购物车</h2>
      <el-button type="danger" size="small" @click="handleClearCart" :disabled="list.length === 0">
        清空购物车
      </el-button>
    </div>

    <el-table
      v-loading="listLoading"
      :data="list"
      element-loading-text="加载中..."
      border
      fit
      highlight-current-row
      style="width: 100%"
    >
      <el-table-column label="商品图片" width="120" align="center">
        <template slot-scope="scope">
          <img :src="scope.row.product && scope.row.product.image ? 'http://localhost:8080/api' + scope.row.product.image : ''" alt="商品图片" style="width: 80px; height: 80px;">
        </template>
      </el-table-column>

      <el-table-column label="商品名称" min-width="150" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.product ? scope.row.product.name : '' }}</span>
        </template>
      </el-table-column>

      <el-table-column label="品牌" width="120" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.product ? scope.row.product.brandName : '' }}</span>
        </template>
      </el-table-column>

      <el-table-column label="单价" width="120" align="center">
        <template slot-scope="scope">
          <span>¥{{ scope.row.product ? scope.row.product.price : 0 }}</span>
        </template>
      </el-table-column>

      <el-table-column label="数量" width="150" align="center">
        <template slot-scope="scope">
          <el-input-number
            v-model="scope.row.quantity"
            :min="1"
            :max="10"
            size="mini"
            @change="handleQuantityChange(scope.row)"
          />
        </template>
      </el-table-column>

      <el-table-column label="小计" width="120" align="center">
        <template slot-scope="scope">
          <span>¥{{ scope.row.product ? (scope.row.product.price * scope.row.quantity).toFixed(2) : '0.00' }}</span>
        </template>
      </el-table-column>

      <el-table-column label="操作" width="120" align="center">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="danger"
            @click="handleDelete(scope.row)"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <div class="cart-footer">
      <div class="cart-total">
        <span>总计：</span>
        <span class="price">¥{{ totalPrice.toFixed(2) }}</span>
      </div>
      <el-button type="primary" @click="handleCheckout" :disabled="list.length === 0">
        去结算
      </el-button>
    </div>

    <!-- 结算对话框 -->
    <el-dialog title="订单确认" :visible.sync="checkoutDialogVisible" width="500px">
      <el-form :model="orderForm" label-width="120px">
        <el-form-item label="收货地址">
          <el-input v-model="orderForm.address" placeholder="请输入收货地址"></el-input>
        </el-form-item>
        <el-form-item label="联系电话">
          <el-input v-model="orderForm.phone" placeholder="请输入联系电话"></el-input>
        </el-form-item>
        <el-form-item label="备注">
          <el-input type="textarea" v-model="orderForm.remark" placeholder="请输入备注信息"></el-input>
        </el-form-item>
      </el-form>
      <div class="checkout-total">
        <span>订单总价：</span>
        <span class="price">¥{{ totalPrice.toFixed(2) }}</span>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="checkoutDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitOrder" :loading="submitLoading">提交订单</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getCartList, updateCartItem, deleteCartItem, clearCart } from '@/api/cart'
import { createOrder } from '@/api/order'

export default {
  name: 'Cart',
  data() {
    return {
      list: [],
      listLoading: true,
      checkoutDialogVisible: false,
      submitLoading: false,
      orderForm: {
        address: '',
        phone: '',
        remark: ''
      }
    }
  },
  computed: {
    totalPrice() {
      return this.list.reduce((total, item) => {
        return total + (item.product ? item.product.price * item.quantity : 0)
      }, 0)
    }
  },
  created() {
    this.getList()
    // 获取用户信息，填充地址和电话
    const userInfo = {
      address: localStorage.getItem('userAddress') || '',
      phone: localStorage.getItem('userPhone') || ''
    }
    this.orderForm.address = userInfo.address
    this.orderForm.phone = userInfo.phone
  },
  methods: {
    getList() {
      this.listLoading = true
      getCartList().then(response => {
        this.list = response.data
        this.listLoading = false
      })
    },
    handleQuantityChange(row) {
      updateCartItem(row.id, row.quantity).then(() => {
        this.$message({
          message: '更新数量成功',
          type: 'success',
          duration: 2000
        })
      }).catch(error => {
        console.error('更新数量失败:', error)
      })
    },
    handleDelete(row) {
      this.$confirm('确认删除该商品吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        deleteCartItem(row.id).then(() => {
          this.$message({
            message: '删除成功',
            type: 'success',
            duration: 2000
          })
          this.getList()
        })
      }).catch(() => {})
    },
    handleClearCart() {
      this.$confirm('确认清空购物车吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        clearCart().then(() => {
          this.$message({
            message: '清空购物车成功',
            type: 'success',
            duration: 2000
          })
          this.getList()
        })
      }).catch(() => {})
    },
    handleCheckout() {
      this.checkoutDialogVisible = true
    },
    submitOrder() {
      this.submitLoading = true
      
      // 获取购物车ID列表
      const cartIds = this.list.map(item => item.id)
      
      createOrder({
        address: this.orderForm.address,
        phone: this.orderForm.phone,
        remark: this.orderForm.remark,
        totalAmount: this.totalPrice,
        cartIds: cartIds
      }).then(response => {
        this.$message({
          message: '订单提交成功',
          type: 'success',
          duration: 2000
        })
        this.checkoutDialogVisible = false
        this.submitLoading = false
        // 清空购物车
        this.getList()
        // 跳转到订单页面
        this.$router.push('/customer/orders')
      }).catch(error => {
        console.error('提交订单失败:', error)
        this.$message({
          message: '提交订单失败，请检查信息是否完整',
          type: 'error',
          duration: 2000
        })
        this.submitLoading = false
      })
    }
  }
}
</script>

<style scoped>
.cart-container {
  padding: 20px;
}

.cart-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.cart-header h2 {
  margin: 0;
}

.cart-footer {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
  align-items: center;
}

.cart-total {
  margin-right: 20px;
  font-size: 16px;
}

.price {
  color: #f56c6c;
  font-weight: bold;
  font-size: 20px;
}

.checkout-total {
  text-align: right;
  margin-top: 20px;
  font-size: 16px;
}
</style> 